<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useBlogStore } from '@/store/blog'
import { useTypeStore } from '@/store/type'
import { useAuthStore } from '@/store/auth'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import 'highlight.js/styles/monokai.css'
import hljs from 'highlight.js'
import javascript from 'highlight.js/lib/languages/javascript'
import python from 'highlight.js/lib/languages/python'
import java from 'highlight.js/lib/languages/java'
import xml from 'highlight.js/lib/languages/xml'
import css from 'highlight.js/lib/languages/css'

// 注册常用的编程语言
hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('python', python)
hljs.registerLanguage('java', java)
hljs.registerLanguage('xml', xml)
hljs.registerLanguage('css', css)

// 配置 Quill 的代码高亮
const highlightCode = (text) => {
  try {
    return hljs.highlightAuto(text).value
  } catch (e) {
    console.error('代码高亮处理失败:', e)
    return text
  }
}

const router = useRouter()
const blogStore = useBlogStore()
const typeStore = useTypeStore()
const authStore = useAuthStore()

const title = ref('')
const content = ref('')
const selectedType = ref(null)
const blogTypes = ref([])
const coverImage = ref(null)
const coverImagePreview = ref('')
const description = ref('')
const tags = ref('')
const status = ref('published')
const loading = ref(false)
const submitStatus = ref({
  submitting: false,
  success: false,
  error: false,
  message: ''
})
const editorHeight = ref('100%')

// 新增类型相关状态
const showTypeModal = ref(false)
const newTypeName = ref('')
const typeSubmitting = ref(false)
const typeMessage = ref('')
const typeMessageType = ref('')

// 图片处理函数
const imageHandler = () => {
  const input = document.createElement('input')
  input.setAttribute('type', 'file')
  input.setAttribute('accept', 'image/*')
  input.click()

  input.onchange = async () => {
    const file = input.files[0]
    
    if (file) {
      try {
        // 检查文件大小
        if (file.size > 5 * 1024 * 1024) {
          alert('图片大小不能超过5MB')
          return
        }

        // 压缩图片
        const compressedImage = await compressImage(file)
        
        // 创建 FormData
        const formData = new FormData()
        formData.append('image', compressedImage)
        
        // 上传图片
        const response = await fetch('http://localhost:8080/api/image/upload', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: formData
        })
        
        if (!response.ok) {
          throw new Error('图片上传失败')
        }
        
        const result = await response.json()
        
        // 获取编辑器实例
        const quill = document.querySelector('.ql-editor').__vue__.$parent.quill
        
        // 获取当前光标位置
        const range = quill.getSelection(true)
        
        // 在光标位置插入图片
        quill.insertEmbed(range.index, 'image', `http://localhost:8080/api/image/${result.imageName}`)
        
        // 将光标移动到图片后面
        quill.setSelection(range.index + 1)
      } catch (error) {
        console.error('图片上传失败:', error)
        alert('图片上传失败，请重试')
      }
    }
  }
}

// 富文本编辑器配置
const editorConfig = {
  placeholder: '在这里输入博客内容...',
  modules: {
    toolbar: {
      container: [
        [{ 'font': [] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'align': [] }],
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        [{ 'indent': '-1'}, { 'indent': '+1' }],
        [{ 'script': 'sub'}, { 'script': 'super' }],
        ['blockquote', 'code-block'],
        ['link', 'image', 'video'],
        [{ 'direction': 'rtl' }],
        ['clean']
      ],
      handlers: {
        image: imageHandler
      }
    },
    syntax: {
      highlight: highlightCode
    },
    clipboard: {
      matchVisual: false
    }
  }
}

// 添加自动保存功能
const autoSaveInterval = ref(null)
const lastSavedContent = ref('')

onMounted(async () => {
  if (!authStore.isAuthenticated) {
    router.push('/login')
    return
  }
  
  try {
    loading.value = true
    await loadBlogTypes()
    
    // 启动自动保存
    autoSaveInterval.value = setInterval(() => {
      if (content.value && content.value !== lastSavedContent.value) {
        localStorage.setItem('blog_draft', JSON.stringify({
          title: title.value,
          content: content.value,
          description: description.value,
          type: selectedType.value,
          timestamp: Date.now()
        }))
        lastSavedContent.value = content.value
      }
    }, 30000)
    
    // 尝试恢复草稿
    const savedDraft = localStorage.getItem('blog_draft')
    if (savedDraft) {
      const draft = JSON.parse(savedDraft)
      const timestamp = new Date(draft.timestamp)
      const now = new Date()
      const hoursDiff = (now - timestamp) / (1000 * 60 * 60)
      
      if (hoursDiff < 24) {
        if (confirm('发现未发布的草稿，是否恢复？')) {
          title.value = draft.title
          content.value = draft.content
          description.value = draft.description
          selectedType.value = draft.type
        }
      }
      localStorage.removeItem('blog_draft')
    }
  } catch (error) {
    console.error('Failed to load blog types:', error)
  } finally {
    loading.value = false
  }
})

onUnmounted(() => {
  if (autoSaveInterval.value) {
    clearInterval(autoSaveInterval.value)
  }
})

const loadBlogTypes = async () => {
  try {
    // 使用typeStore获取用户的博客类型
    const types = await typeStore.getUserBlogTypes()
    blogTypes.value = types || []
    
    if (blogTypes.value.length > 0) {
      selectedType.value = blogTypes.value[0].typeId
    }
  } catch (error) {
    console.error('Failed to load blog types:', error)
  }
}

const openNewTypeModal = () => {
  showTypeModal.value = true
  newTypeName.value = ''
  typeMessage.value = ''
}

const closeNewTypeModal = () => {
  showTypeModal.value = false
}

const createNewType = async () => {
  if (!newTypeName.value.trim()) {
    typeMessage.value = '请输入类型名称'
    typeMessageType.value = 'error'
    return
  }
  
  try {
    typeSubmitting.value = true
    typeMessage.value = ''
    
    // 创建新类型
    const newType = await typeStore.createBlogType(newTypeName.value.trim())
    
    // 刷新类型列表并选择新创建的类型
    await loadBlogTypes()
    selectedType.value = newType.typeId
    
    typeMessage.value = '创建类型成功'
    typeMessageType.value = 'success'
    
    // 短暂延迟后关闭弹窗
    setTimeout(() => {
      closeNewTypeModal()
    }, 1000)
  } catch (error) {
    typeMessage.value = error.message || '创建类型失败'
    typeMessageType.value = 'error'
  } finally {
    typeSubmitting.value = false
  }
}

const handleCoverImageChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 检查文件格式
  const allowedTypes = ['image/jpeg', 'image/png', 'image/webp']
  if (!allowedTypes.includes(file.type)) {
    alert('只支持 JPG、PNG 和 WebP 格式的图片')
    return
  }
  
  if (file.size > 5 * 1024 * 1024) { // 5MB
    alert('图片大小不能超过5MB')
    return
  }
  
  try {
    // 压缩图片
    const compressedImage = await compressImage(file)
    coverImage.value = compressedImage
    
    const reader = new FileReader()
    reader.onload = (e) => {
      coverImagePreview.value = e.target.result
    }
    reader.readAsDataURL(compressedImage)
  } catch (error) {
    console.error('图片处理失败:', error)
    alert('图片处理失败，请重试')
  }
}

// 图片压缩函数
const compressImage = (file) => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = URL.createObjectURL(file)
    img.onload = () => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      
      // 计算压缩后的尺寸，保持宽高比
      let width = img.width
      let height = img.height
      const maxSize = 1200
      
      if (width > height && width > maxSize) {
        height = (height * maxSize) / width
        width = maxSize
      } else if (height > maxSize) {
        width = (width * maxSize) / height
        height = maxSize
      }
      
      canvas.width = width
      canvas.height = height
      ctx.drawImage(img, 0, 0, width, height)
      
      canvas.toBlob((blob) => {
        resolve(new File([blob], file.name, {
          type: file.type,
          lastModified: Date.now()
        }))
      }, file.type, 0.8) // 压缩质量为0.8
    }
    img.onerror = reject
  })
}

const removeCoverImage = () => {
  coverImage.value = null
  coverImagePreview.value = ''
}

const saveAsDraft = () => {
  status.value = 'draft'
  submitBlog()
}

const publish = () => {
  status.value = 'published'
  submitBlog()
}

const handleContentChange = (val) => {
  content.value = val
}

const submitBlog = async () => {
  if (!title.value?.trim()) {
    alert('请输入博客标题')
    return
  }
  
  // 检查内容是否为空
  const contentText = content.value?.html || content.value || ''
  if (!contentText.trim()) {
    alert('请输入博客内容')
    return
  }
  
  if (!selectedType.value) {
    alert('请选择博客分类')
    return
  }
  
  try {
    submitStatus.value.submitting = true
    
    // 构建博客数据
    const formData = new FormData()
    formData.append('title', title.value.trim())
    formData.append('content', contentText.trim())
    formData.append('typeId', selectedType.value)
    formData.append('userId', authStore.user.userId)
    formData.append('isPublished', status.value === 'published')
    
    if (description.value?.trim()) {
      formData.append('summary', description.value.trim())
    }
    
    if (coverImage.value) {
      formData.append('coverImage', coverImage.value, coverImage.value.name)
    }
    
    // 提交博客
    const response = await blogStore.createBlog(formData)
    
    if (response.success) {
      // 清除草稿
      localStorage.removeItem('blog_draft')
      
      submitStatus.value.success = true
      submitStatus.value.message = '博客创建成功！'
      
      // 重定向到博客详情页
      setTimeout(() => {
        router.push(`/blogs/${response.blogId}`)
      }, 1500)
    } else {
      throw new Error(response.message || '创建博客失败')
    }
  } catch (error) {
    console.error('Failed to create blog:', error)
    submitStatus.value.error = true
    submitStatus.value.message = error.response?.data?.message || error.message || '创建博客失败，请重试。'
  } finally {
    submitStatus.value.submitting = false
  }
}

const cancelCreate = () => {
  if (confirm('确定要取消创建吗？所有未保存的内容将丢失。')) {
    router.push('/user/my-blogs')
  }
}
</script>

<template>
  <div class="create-blog">
    <div class="page-header">
      <h2 class="page-title">创建新博客</h2>
      <div class="auto-save-status" v-if="lastSavedContent">
        上次保存: {{ new Date().toLocaleTimeString() }}
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
    </div>
    
    <template v-else>
      <div class="blog-form-container">
        <!-- 左侧主要内容 -->
        <div class="main-content">
          <!-- 标题输入 -->
          <div class="card blog-form-card title-card">
            <input 
              type="text" 
              v-model="title" 
              class="title-input" 
              placeholder="请输入博客标题"
              maxlength="100"
            />
            <div class="char-counter">{{ title.length }}/100</div>
          </div>
          
          <!-- 博客内容编辑器 -->
          <div class="card blog-form-card editor-card">
            <div class="editor-container">
              <QuillEditor
                v-model:content="content"
                :options="editorConfig"
                contentType="html"
                theme="snow"
                @update:content="handleContentChange"
              />
            </div>
          </div>
        </div>
        
        <!-- 右侧边栏 -->
        <div class="sidebar">
          <!-- 发布设置卡片 -->
          <div class="card blog-form-card">
            <h3 class="card-title">发布设置</h3>
            
            <div class="form-group">
              <label class="form-label required">博客分类</label>
              <div class="type-select-container">
                <select 
                  v-model="selectedType" 
                  class="form-input"
                >
                  <option value="" disabled>请选择分类</option>
                  <option 
                    v-for="type in blogTypes" 
                    :key="type.typeId" 
                    :value="type.typeId"
                  >
                    {{ type.typeName }}
                  </option>
                </select>
                <button 
                  type="button" 
                  class="btn btn-icon" 
                  @click="openNewTypeModal"
                  title="添加新分类"
                >
                  <i class="fas fa-plus"></i>
                </button>
              </div>
            </div>
            
            <div class="form-group">
              <label class="form-label">博客摘要</label>
              <textarea 
                v-model="description" 
                class="form-input textarea" 
                placeholder="请输入博客摘要（可选）"
                maxlength="200"
                rows="3"
              ></textarea>
              <div class="char-counter">{{ description.length }}/200</div>
            </div>
            
            <!-- 封面图片上传 -->
            <div class="form-group">
              <label class="form-label">封面图片</label>
              <div class="cover-image-container">
                <div 
                  v-if="coverImagePreview" 
                  class="cover-image-preview"
                >
                  <img :src="coverImagePreview" alt="封面预览" />
                  <button 
                    class="btn-remove-image" 
                    title="移除图片"
                    @click="removeCoverImage"
                  >
                    ×
                  </button>
                </div>
                
                <div v-else class="cover-image-upload">
                  <label for="cover-image" class="upload-label">
                    <div class="upload-icon">📷</div>
                    <div class="upload-text">点击上传封面图片</div>
                    <div class="upload-hint">推荐尺寸: 1200 x 600，大小不超过5MB</div>
                  </label>
                  <input 
                    type="file" 
                    id="cover-image" 
                    @change="handleCoverImageChange" 
                    accept="image/jpeg,image/png,image/webp" 
                    hidden
                  />
                </div>
              </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="form-actions">
              <button 
                class="btn btn-secondary" 
                @click="cancelCreate"
              >
                取消
              </button>
              <button 
                class="btn btn-outline-primary" 
                @click="saveAsDraft" 
                :disabled="submitStatus.submitting"
              >
                <span v-if="submitStatus.submitting && status === 'draft'" class="loading-spinner-small"></span>
                <span v-else>存草稿</span>
              </button>
              <button 
                class="btn btn-primary" 
                @click="publish" 
                :disabled="submitStatus.submitting"
              >
                <span v-if="submitStatus.submitting && status === 'published'" class="loading-spinner-small"></span>
                <span v-else>发布</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </template>
    
    <!-- 创建类型的弹窗 -->
    <Teleport to="body">
      <div v-if="showTypeModal" class="modal-overlay" @click.self="closeNewTypeModal">
        <div class="modal-container">
          <div class="modal-header">
            <h3>创建新分类</h3>
            <button class="btn-icon" @click="closeNewTypeModal">
              <i class="fas fa-times"></i>
            </button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label class="form-label required">分类名称</label>
              <input 
                type="text" 
                v-model="newTypeName" 
                class="form-input" 
                placeholder="请输入分类名称"
                maxlength="20"
                @keyup.enter="createNewType"
              />
            </div>
            <div v-if="typeMessage" :class="['message', typeMessageType]">
              {{ typeMessage }}
            </div>
          </div>
          <div class="modal-footer">
            <button 
              class="btn btn-secondary" 
              @click="closeNewTypeModal"
              :disabled="typeSubmitting"
            >
              取消
            </button>
            <button 
              class="btn btn-primary" 
              @click="createNewType"
              :disabled="typeSubmitting"
            >
              <span v-if="typeSubmitting" class="loading-spinner-small"></span>
              <span v-else>创建</span>
            </button>
          </div>
        </div>
      </div>
    </Teleport>
    
    <!-- 提交状态信息 -->
    <div v-if="submitStatus.success || submitStatus.error" 
         :class="['submit-status', { 'success': submitStatus.success, 'error': submitStatus.error }]">
      {{ submitStatus.message }}
    </div>
  </div>
</template>

<style scoped>
.create-blog {
  min-height: calc(100vh - var(--header-height));
  padding: 2rem;
  background-color: var(--background-color);
  display: flex;
  flex-direction: column;
  height: calc(100vh - var(--header-height));
  overflow: hidden;
}

.page-header {
  margin-bottom: 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-color);
  margin: 0;
}

.auto-save-status {
  font-size: 0.9rem;
  color: var(--text-light);
}

.blog-form-container {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 320px;
  gap: 2rem;
  flex: 1;
  overflow: hidden;
  height: 100%;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 2rem;
  overflow: hidden;
  height: 100%;
}

.title-card {
  padding: 1.5rem;
  flex-shrink: 0;
  height: auto;
  background: var(--background-dark);
  border-radius: 8px;
  box-shadow: var(--card-shadow);
}

.title-input {
  width: 100%;
  border: none;
  outline: none;
  font-size: 1.75rem;
  font-weight: 600;
  padding: 0;
  background: transparent;
  color: var(--text-color);
}

.title-input::placeholder {
  color: var(--text-light);
}

.editor-card {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: var(--background-dark);
  border-radius: 8px;
  box-shadow: var(--card-shadow);
  min-height: 0; /* 重要：允许flex子元素收缩 */
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0; /* 重要：允许flex子元素收缩 */
}

:deep(.ql-container) {
  flex: 1;
  overflow-y: auto;
  font-size: 1rem;
  font-family: var(--font-family);
}

:deep(.ql-toolbar) {
  border-top: none !important;
  border-left: none !important;
  border-right: none !important;
  border-bottom: 1px solid var(--border-color) !important;
  padding: 0.75rem 1rem !important;
  background-color: var(--background-light, #f8f9fa);
  flex-shrink: 0;
}

:deep(.ql-editor) {
  padding: 2rem;
  min-height: 100%;
  font-size: 1rem;
  line-height: 1.8;
  overflow-y: auto;
}

.sidebar {
  height: 100%;
  overflow-y: auto;
  padding-right: 0.5rem;
  margin-right: -0.5rem;
}

/* 自定义滚动条样式 */
.sidebar::-webkit-scrollbar,
:deep(.ql-editor)::-webkit-scrollbar {
  width: 6px;
}

.sidebar::-webkit-scrollbar-thumb,
:deep(.ql-editor)::-webkit-scrollbar-thumb {
  background-color: var(--border-color);
  border-radius: 3px;
}

.sidebar::-webkit-scrollbar-track,
:deep(.ql-editor)::-webkit-scrollbar-track {
  background-color: transparent;
}

.card-title {
  font-size: 1.1rem;
  font-weight: 500;
  margin-bottom: 1.5rem;
  padding-bottom: 0.75rem;
  border-bottom: 1px solid var(--border-color);
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  font-size: 0.95rem;
}

.form-label.required:after {
  content: " *";
  color: var(--error-color);
}

.form-input {
  display: block;
  width: 100%;
  padding: 0.75rem 1rem;
  font-size: 0.95rem;
  border: 1.5px solid var(--border-color);
  border-radius: 6px;
  background-color: var(--background);
  transition: all 0.2s;
}

.form-input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(var(--primary-color-rgb), 0.1);
}

.textarea {
  resize: vertical;
  min-height: 100px;
}

.char-counter {
  text-align: right;
  margin-top: 0.25rem;
  font-size: 0.85rem;
  color: var(--text-light);
}

.type-select-container {
  display: flex;
  gap: 0.75rem;
  align-items: center;
}

.type-select-container .form-input {
  flex: 1;
}

.btn-icon {
  width: 36px;
  height: 36px;
  padding: 0;
  border: 1.5px solid var(--border-color);
  border-radius: 6px;
  background: transparent;
  color: var(--text-color);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.btn-icon:hover {
  border-color: var(--primary-color);
  color: var(--primary-color);
  background: rgba(var(--primary-color-rgb), 0.05);
}

.cover-image-container {
  width: 100%;
  aspect-ratio: 2 / 1;
  border-radius: 8px;
  overflow: hidden;
  border: 2px dashed var(--border-color);
}

.cover-image-preview {
  width: 100%;
  height: 100%;
  position: relative;
}

.cover-image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.btn-remove-image {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  width: 2rem;
  height: 2rem;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  font-size: 1.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  backdrop-filter: blur(4px);
}

.btn-remove-image:hover {
  background-color: var(--error-color);
  transform: scale(1.1);
}

.cover-image-upload {
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.upload-label {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 0.75rem;
  cursor: pointer;
}

.upload-icon {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
}

.upload-text {
  font-size: 1.1rem;
  font-weight: 500;
}

.upload-hint {
  font-size: 0.85rem;
  color: var(--text-light);
}

.form-actions {
  display: flex;
  gap: 0.75rem;
  margin-top: 2rem;
}

.form-actions .btn {
  flex: 1;
}

.submit-status {
  position: fixed;
  bottom: 2rem;
  left: 50%;
  transform: translateX(-50%);
  padding: 1rem 2rem;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 100;
  animation: slideUp 0.3s ease;
}

.submit-status.success {
  background-color: var(--success-color);
  color: white;
}

.submit-status.error {
  background-color: var(--error-color);
  color: white;
}

/* Modal styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  width: 90%;
  max-width: 400px;
  background: var(--background-dark);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  animation: modalShow 0.3s ease;
}

.modal-header {
  padding: 1rem 1.25rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid var(--border-color);
}

.modal-header h3 {
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0;
}

.modal-body {
  padding: 1.25rem;
}

.modal-footer {
  padding: 1rem 1.25rem;
  display: flex;
  justify-content: flex-end;
  gap: 0.75rem;
  border-top: 1px solid var(--border-color);
}

@keyframes modalShow {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes slideUp {
  from {
    transform: translate(-50%, 100%);
    opacity: 0;
  }
  to {
    transform: translate(-50%, 0);
    opacity: 1;
  }
}

/* Responsive styles */
@media (max-width: 1024px) {
  .create-blog {
    height: auto;
    overflow: visible;
  }

  .blog-form-container {
    grid-template-columns: 1fr;
    height: auto;
    overflow: visible;
  }
  
  .main-content {
    height: auto;
    overflow: visible;
  }

  .editor-card {
    height: 600px; /* 在移动端设置固定高度 */
  }
  
  .sidebar {
    height: auto;
    overflow: visible;
  }
}

@media (max-width: 768px) {
  .create-blog {
    padding: 1rem;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .title-input {
    font-size: 1.5rem;
  }
  
  .editor-card {
    height: 400px; /* 在小屏幕上减小高度 */
  }

  :deep(.ql-editor) {
    padding: 1rem;
  }
}

/* 暗色主题适配 */
[data-theme='dark'] :deep(.ql-toolbar),
[data-theme='dark'] :deep(.ql-container) {
  border-color: var(--border-color) !important;
}

[data-theme='dark'] :deep(.ql-stroke) {
  stroke: var(--text-color) !important;
}

[data-theme='dark'] :deep(.ql-fill) {
  fill: var(--text-color) !important;
}

[data-theme='dark'] :deep(.ql-picker-label) {
  color: var(--text-color) !important;
}

/* 编辑器样式优化 */
:deep(.ql-toolbar.ql-snow) {
  border-top: none;
  border-left: none;
  border-right: none;
  border-bottom: 1px solid var(--border-color);
  padding: 1rem;
  background-color: var(--background-light);
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

:deep(.ql-toolbar.ql-snow .ql-formats) {
  margin-right: 1rem;
}

:deep(.ql-container.ql-snow) {
  border: none;
  font-family: var(--font-family);
}

:deep(.ql-editor h1) {
  font-size: 2em;
  margin-bottom: 1em;
}

:deep(.ql-editor h2) {
  font-size: 1.5em;
  margin-bottom: 0.8em;
}

:deep(.ql-editor h3) {
  font-size: 1.17em;
  margin-bottom: 0.67em;
}

:deep(.ql-editor p) {
  margin-bottom: 1em;
}

:deep(.ql-editor blockquote) {
  border-left: 4px solid var(--primary-color);
  padding-left: 1em;
  margin: 1em 0;
  color: var(--text-light);
}

:deep(.ql-editor pre) {
  background: var(--background-dark);
  border-radius: 6px;
  padding: 1em;
  margin: 1em 0;
}

:deep(.ql-editor code) {
  font-family: 'Fira Code', monospace;
  background: var(--background-dark);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-size: 0.9em;
}

:deep(.ql-editor img) {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 1em auto;
  border-radius: 6px;
}

:deep(.ql-snow .ql-tooltip) {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 0.5rem;
}

:deep(.ql-snow .ql-tooltip input[type=text]) {
  border: 1px solid var(--border-color);
  border-radius: 4px;
  padding: 0.3rem 0.5rem;
  font-size: 0.9rem;
  width: 200px;
}

/* 暗色主题适配 */
[data-theme='dark'] {
  :deep(.ql-snow .ql-stroke) {
    stroke: var(--text-color);
  }
  
  :deep(.ql-snow .ql-fill) {
    fill: var(--text-color);
  }
  
  :deep(.ql-snow .ql-picker) {
    color: var(--text-color);
  }
  
  :deep(.ql-snow .ql-picker-options) {
    background-color: var(--background-dark);
    border-color: var(--border-color);
  }
  
  :deep(.ql-toolbar.ql-snow) {
    border-color: var(--border-color);
  }
  
  :deep(.ql-container.ql-snow) {
    border-color: var(--border-color);
  }
  
  :deep(.ql-editor code) {
    background-color: rgba(255, 255, 255, 0.1);
  }
}
</style> 